import { createSlice } from '@reduxjs/toolkit'
import { getDjRadioCategory, getDjRadioRecommend,getDjRadios } from '../service/djradio'
import { createAsyncThunk } from '@reduxjs/toolkit'
import type { djRadioCategoryType, djRadioRecommendType, djRadioRankingType } from './type'

export const fetchDjRadioCategoryAction = createAsyncThunk(
  'djRadioCategory',
  async (arg, { dispatch }) => {
    getDjRadioCategory().then((res) => {
      console.log(res, 'djRadioCategory')
      dispatch(changeDjRadioCategoryAction(res.categories))
    })
  }
)

export const fetchDjRadioRecommendAction = createAsyncThunk(
  'djRadioRecommend',
  async (type: number, { dispatch }) => {
    getDjRadioRecommend(type).then((res) => {
      console.log(res.djRadios, 'djRadioRecommend')
      const recommendData = Array.isArray(res.djRadios) ? res.djRadios : [res.djRadios];
      dispatch(changeDjRadioRecommendAction(recommendData))
    })
  }
)


export const  fetchDjRadioRankingAction = createAsyncThunk(
  'djRadioRanking',
  async (params: { cateId: number, limit: number, offset: number }, { dispatch }) => {
    getDjRadios(params.cateId, params.limit, params.offset).then((res) => {
      console.log(res, 'djRadioRanking')
      dispatch(changeDjRadioRankingAction(res.djRadios))
      dispatch(changeDjRadioRankingTotalAction(res.count || res.total || 0))
    })
  }
)

export interface DjRadioState {
  djRadioCategory: djRadioCategoryType[]
  currentId: number
  djRadioRecommend: djRadioRecommendType[]
  djRadioRanking: djRadioRankingType[]
  PER_PAGE_NUMBER: number
  djRadioRankingTotal: number
}

export const initialState: DjRadioState = {
  djRadioCategory: [],
  currentId: 0,
  djRadioRecommend: [],
  djRadioRanking: [],
  PER_PAGE_NUMBER: 35,
  djRadioRankingTotal: 0,
}

const djRadioSlice = createSlice({
  name: 'djradio',
  initialState,
  reducers: {
    changeDjRadioCategoryAction(state, { payload }) {
      state.djRadioCategory = payload
    },
    changeCurrentIdAction(state, { payload }) {
      state.currentId = payload
    },
    changeDjRadioRecommendAction(state, { payload }) {
      state.djRadioRecommend = payload
    },
    changeDjRadioRankingAction(state, { payload }) {
      state.djRadioRanking = payload
    },
    changeDjRadioRankingTotalAction(state, { payload }) {
      state.djRadioRankingTotal = payload
    }

  }
})
export const {
  changeDjRadioCategoryAction,
  changeCurrentIdAction,
  changeDjRadioRecommendAction,
  changeDjRadioRankingAction,
  changeDjRadioRankingTotalAction
} = djRadioSlice.actions
export default djRadioSlice.reducer
